<?php

class RestV1
{
	
  // public myspaceContext
   
  public $context = NULL;
  
  /**
   * Sets up the Rest V1 with MySpace Context
   *
   * @param MySpaceContext $context
   * @return object a new restv1 object
   */
  public function __construct($context)  {
     $this->context = $context;
  }
  
	/**
   * RESTurl: http://api.myspace.com/v1/user
   * Gets the MySpace UserId of the user represented by the token
   *
   * @return String value extracted from the response
   */
  public function getCurrentUserId(){
  	$REST = "http://api.myspace.com/v1/user".'.json';
  	$params = NULL;

  	$responseJSON = $this->context->call($REST,$params, 'GET');

  	//parseJSON is a static method and does not effect the object
  	$currentUser = MySpaceUtils::parseJSON($responseJSON);
  	return $currentUser->userId;
  }

  /**
   * REST Notes: http://api.myspace.com/v1/users/{userId}/albums
   *
   * Gets the MySpace UserId of the user represented by the tokenReturns the photo
   *  album data for the user specified by userid.
   *
   * Returns the dynamically generated "Albums" "shallow object" that contains
   *  the user's photo album information. The field names of the object will be
   *  identical to those that are returned in a direct REST API call.
   *
   *
   * @param $userId: The user's MySpace user ID
   * @param $page: Specifies the sequential page number starting from 1. If not specified, defaults to 1
   * @param $pageSize: Specifies the number of albumsper page. If not specified, defaults to 20. Setting the pageSize parameter to "all" will give the entire list
   *
   * @return String value extracted from the response
   */
  public function getAlbums($userId, $page=1, $pageSize=20){
  	$REST = "http://api.myspace.com/v1/users/".$userId."/albums".'.json';


  	//set the params
  	$params = array( //if $page is null or empty, use the default, else use $page
  				'page' => (empty($page) ? 1 : $page),
  				'pageSize' => (empty($pageSize) ? 20 : $pageSize)
  				);



  	$responseJSON = $this->context->call($REST,$params, 'GET');

  	//parseJSON is a static method and does not effect the object
  	return MySpaceUtils::parseJSON($responseJSON);
  }

  /**
   * The function will get all of the activites of a given user, provided that the current user and application have privilages to access it
   *
   * @param int|string $userId
   * @param unknown_type $culture
   * @param mixed $datetime A better limit on the activities returned is datetime because it allows the consumer to query 
   * 						deltas and only processed what has changed. Pass a date that is less than 60 days ago as the maximum and default number of days back you can query is 60. 
   * 						If you query more than that the system will only go as far back as 60. Example of querystring parameters is: datetime=06/21/2009
   * 
   * @param string $activityTypes PhotoTagged|PhotoAdd|SongUpload|ProfileSongAdd|BlogAdd|ForumPosted|ForumTopicReply|VideoAdd|ProfileVideoUpdate|FavoriteVideoAdd|FriendAdd|JoinedGroup|FriendCategoryAdd|PersonalBandShowUpdate|EventPosting|EventAttending|ApplicationAdd
   * @param int    $pageSize      You can use this parameter to specify the number of atom entries returned in the stream
   * @param bool   $composite	  Set this parameter to true to get one atom entry for all activities of the same type on the same day. If the objects of the activities go into targets then they will be grouped by target. Ex: Max uploaded 5 photos into the album Medieval Times.
   * @param bool   $extensions    Pipe delimited list of options syndicating the activity stream. Name fo the query string parameter is "extensions" Example: &extensions=actor|subject
   * 
   * @return SimpleXML a SimpleXML representation of an Activities ATOM Feed
   */
  public function getActivities_ATOM($userId, $culture=null, $datetime=null, $activityTypes=null, $pageSize=null, $composite=null, $extensions=null){
  	//see getFriendsActivities_ATOM for activity types

  	$REST = "http://api.myspace.com/v1/users/".$userId."/activities.atom";
	//$REST = "http://api.myspace.com/v1/users/".$userId."/activities".'.atom';


  	//set the params
  	$params = array( 'culture' => $culture,
  					 'datetime' => $datetime,
  					 'activitytypes' => $activityTypes,
  					 'page_size' => $pageSize,
  					 'composite' => $compisite,
  					 'extensions' => $extensions
  					);

  	$responseATOM = $this->context->call_ATOM($REST, $params, 'GET');

  	//returns a SimpleXML Atom feed.
  	return $responseATOM;
  }
  
  /**
   * The function will get all of the activites of a given user's friends, provided that the current user and application have privilages to access it
   *
   * @param int|string $userId
   * @param unknown_type $culture
   * @param mixed $datetime A better limit on the activities returned is datetime because it allows the consumer to query 
   * 						deltas and only processed what has changed. Pass a date that is less than 60 days ago as the maximum and default number of days back you can query is 60. 
   * 						If you query more than that the system will only go as far back as 60. Example of querystring parameters is: datetime=06/21/2009
   * 
   * @param string $activityTypes PhotoTagged|PhotoAdd|SongUpload|ProfileSongAdd|BlogAdd|ForumPosted|ForumTopicReply|VideoAdd|ProfileVideoUpdate|FavoriteVideoAdd|FriendAdd|JoinedGroup|FriendCategoryAdd|PersonalBandShowUpdate|EventPosting|EventAttending|ApplicationAdd
   * @param int    $pageSize      You can use this parameter to specify the number of atom entries returned in the stream
   * @param bool   $composite	  Set this parameter to true to get one atom entry for all activities of the same type on the same day. If the objects of the activities go into targets then they will be grouped by target. Ex: Max uploaded 5 photos into the album Medieval Times.
   * @param bool   $extensions    Pipe delimited list of options syndicating the activity stream. Name fo the query string parameter is "extensions" Example: &extensions=actor|subject
   * @return SimpleXML a SimpleXML representation of an Activities ATOM Feed
   */
  public function getFriendsActivities_ATOM($userId, $culture=null, $datetime=null, $activityTypes=null, $pageSize=null, $composite=null, $extensions=null){

  	$REST = "http://api.myspace.com/v1/users/".$userId."/friends/activities.atom";
	

  	//culture, lastRetrievalTimeStamp(optional), activitytypes(optional)
  	$params = array( 'culture' => $culture,
  					 'datetime' => $datetime,
  					 'activitytypes' => $activityTypes,
  					 'page_size' => $pageSize,
  					 'composite' => $compisite,
  					 'extensions' => $extensions
  					);

	$responseATOM = $this->context->call_ATOM($REST,$params, 'GET');


  	//returns a SimpleXML Atom feed.
  	return $responseATOM;
  }

 


  /**
   * retrieves all photos for a user's album
   *
   * @param String $userId
   * @param String $albumId
   * @return object a php object representing the JSON
   */
  public function getAlbum($userId, $albumId){
  	$REST = "http://api.myspace.com/v1/users/".$userId."/albums/".$albumId."/photos".'.json';

  	$responseJSON = $this->context->call($REST);

  	//parseJSON is a static method and does not effect the object
  	return MySpaceUtils::parseJSON($responseJSON);

  }
  
  /**
  *
  * @link http://wiki.developer.myspace.com/index.php?title=POST_v1_users_userId_albums
  *
  * @param string $userId		the userId of the current user.
  * @param string $tile			'the title of the album;
  * @param string $location		the location of the album, either geography or some other tag
  * @param string $privacy		'Everyone' | 'FriendsOnly' | 'Me'
  *
  * @return object a PHP object representative of the JSON response
  */
  public function createAlbum($userId, $title, $location=null, $privacy='Everyone'){
  
	  $method = 'POST';
	  $REST = 'http://api.myspace.com/v1/users/'.$userId.'/albums'.'json';
	  
	  $privacyValid = array('Everyone','FriendsOnly','Me');
	  $isPrivacyValid = false;
	  foreach($privacyValid as $test){
		  if($test == $privacy) $isPrivacyValid = true;
	  }
	  if($isPrivacyValid == false) {
		  //raise error
	  }
	  
	  $body = array(
		  'location'=> $location,
		  'title' => $title,
		  'privacy' => $privacy
		  );
	  
	  $response = $this->context->makeOAuthRequest(
		  						$REST,
								null,
								$method,
								array('Content-Type' => 'application/x-www-form-urlencoded'),
								$body
								);
	  
	  if($response['status']== 200|201 ){
		  //lets assume that is JSON since that is what we asked for.
		  return MySpaceUtils::parseJSON($reponse['body']);
	  }
	  return false;
  }

  /**
   * Enter description here...
   *
   * @param String $userId
   * @param int $page
   * @param int $pageSize
   * @param String $list 'top,online,app' must select top, online or app, top is the default response
   * @param String $show 'mood|status|online' can set some combintion there of via vertical pipes '|'
   * @return object a php object representing the JSON which is list of the current user's friends
   */
  public function getFriends(
  					$userId,
  					$page=1,
  					$pageSize=20,
  					$list=NULL,
  					$show='mood|status|online'){

  	$REST = "http://api.myspace.com/v1/users/".$userId."/friends".'.json';

  	//set the params
  	$params = array(
  				'page' => (empty($page) ? 1 : $page), //if $page is null or empty, use the default, else use $page
  				'pageSize' => (empty($pageSize) ? 20 : $pageSize),
  				'list' => $list,
  				'show' => $show
  				);

  	$responseJSON = $this->context->call($REST, $params, 'GET');

  	//parseJSON is a static method and does not effect the object
  	return MySpaceUtils::parseJSON($responseJSON);


  }

  /**
   * describes if $userId and $friendsId are currently friends
   *
   * @param String $userId
   * @param int $friendsId
   * @return object an object with a boolean that describes if $userId and $friendsId are currently friends
   */
  public function getFriendship($userId, $friendsId){
  	$REST = 'http://api.myspace.com/v1/users/'.$userId.'/friends/'.$friendsId.'.json';

  	$responseJSON = $this->context->call($REST);

  	//parseJSON is a static method and does not effect the object
  	return MySpaceUtils::parseJSON($responseJSON);

  }

  /**
   * gets the mood of the current user
   *
   * @param String $userId
   * @return object the mood of the current user
   */
  public function getMood($userId){
  	$REST = 'http://api.myspace.com/v1/users/'.$userId.'/mood'.'.json';

  	$responseJSON = $this->context->call($REST);

  	//parseJSON is a static method and does not effect the object
  	return MySpaceUtils::parseJSON($responseJSON);

  }

  /**
   * gets a list of all of the current users photos
   *
   * @param String $userId
   * @param int $page
   * @param int $pageSize
   * @return object a list containing all of the current users photos
   */
  public function getPhotos( $userId, $page=1, $pageSize=20){

  	$REST = 'http://api.myspace.com/v1/users/'.$userId.'/photos'.'.json';

  	$responseJSON = $this->context->call($REST);

  	//parseJSON is a static method and does not effect the object
  	return MySpaceUtils::parseJSON($responseJSON);

  }

  /**
   * gets the meta data for a specific photoid
   *
   * @param String $userId
   * @param String $photoId
   * @return object the meta data for a specific photoid
   */
  public function getPhoto( $userId, $photoId){
  	$REST = 'http://api.myspace.com/v1/users/'.$userId.'/photos/'.$photoId.'.json';

  	$responseJSON = $this->context->call($REST);

  	//parseJSON is a static method and does not effect the object
  	return MySpaceUtils::parseJSON($responseJSON);

  }

  /**
   * gets a user's profile, the object type changes depending on the detail type
   * you are better off useing getProfileBasic(), getProfileFull(), or getProfileExtended()
   *
   * @param String $userId
   * @param String $detailtype 'full' or 'basic' or 'extended' determines request and return type
   * @return mixed a users profile, which can be of type ProfileFull, ProfileBasic, or ProfileExtended
   */
  public function getProfile( $userId, $detailtype = 'full' ){
  	$REST = 'http://api.myspace.com/v1/users/'.$userId.'/profile'.'.json';
	
	//default to full
	$detailType = ($detailtype == 'full'||'extended'||'basic') ? $detailtype : 'full';
	
	//requires a GET request, POST does not work
  	$responseJSON = $this->context->call($REST, array('detailtype' => $detailType), 'GET' );

	//requires a GET request, POST does not work

  	//parseJSON is a static method and does not effect the object
  	return MySpaceUtils::parseJSON($responseJSON);

  }
  /**
  * gets a basic user profile given the userid
  * @param string $userId
  * @return ProfileBasic
  */
  public function getProfileBasic( $userId ){ getProfile($userId, 'basic'); }
  /**
  * gets a full user profile given the userid
  * @param string $userId
  * @return ProfileFull
  */
  public function getProfileFull( $userId ){ getProfile($userId, 'full'); }
  /**
  * gets an extended user profile given a userid
  * @param string $userId
  * @return ProfileExtended
  */
  public function getProfileExtended( $userId ){ getProfile($userId, 'extended'); }

  /**
   * gets a user's status
   *
   * @param String $userId
   * @return object a php object that represents the JSON
   */
  public function getStatus( $userId ){
  	$REST = 'http://api.myspace.com/v1/users/'.$userId.'/status'.'.json';

  	$responseJSON = $this->context->call($REST);

  	//parseJSON is a static method and does not effect the object
  	return MySpaceUtils::parseJSON($responseJSON);

  }
  /**
  * Updates/ Adds a User's status
  * 
  * @param string $userId the userId of the current user or one of their friends
  * @param string $newStatus	the new status to post to the users profile
  * @return boolean returns true if the server response is a 200 or 201, else it returns false
  */
  public function updateStatus($userId, $newStatus){
	//this is done on an XML endpoint because .json might return a 405 error
	$REST = 'http://api.myspace.com/v1/users/'.$userId.'/status';
	$body = array('status' => $newStatus);
  	return $this->context->doPut($REST, $body, 'PUT');
  }
  
  /**
   * gets a list of the current users videos
   *
   * @param String $userId
   * @return object
   */
  public function getVideos( $userId ){
  	$REST = 'http://api.myspace.com/v1/users/'.$userId.'/videos'.'.json';

  	$responseJSON = $this->context->call($REST);

  	//parseJSON is a static method and does not effect the object
  	return MySpaceUtils::parseJSON($responseJSON);

  }

  /**
   * gets the meta data for a specific userid, and videoid
   *
   * @param String $userId
   * @param String $videoId
   * @return object meta data about a specific video
   */
  public function getVideo( $userId, $videoId ){
  	$REST = 'http://api.myspace.com/v1/users/'.$userId.'/videos/'.$videoId.'.json';

  	$responseJSON = $this->context->call($REST);

  	//parseJSON is a static method and does not effect the object
  	return MySpaceUtils::parseJSON($responseJSON);

  }

  /**
   * Gets info about an album.
   * @param String $userId
   * @param String $albumId
   * @return object meta data about an album
   */
  public function getAlbumInfo($userId, $albumId) {
  	$REST = 'http://api.myspace.com/v1/users/'.$userId.'/albums/'.$albumId.'.json';

  	$responseJSON = $this->context->call($REST);

  	//parseJSON is a static method and does not effect the object
  	return MySpaceUtils::parseJSON($responseJSON);
  }
  
  /**
   * Gets info about a photo in an album.
   * @param String $userId
   * @param String $albumId
   * @param String $photoId
   * @return object meta data about a photo in an album
   */
  public function getAlbumPhoto($userId, $albumId, $photoId) {
  	$REST = 'http://api.myspace.com/v1/users/'.$userId.'/albums/'.$albumId.'/photos/'.$photoId.'.json'; 
 	$responseJSON = $this->context->call($REST);
  	return MySpaceUtils::parseJSON($responseJSON);
  }
  
	/**
	 * Posts a notification to a list of recipients.  At most 1000 recipients can be specified.  You will need to pass in 
	 * a template, which specifies the text in the notification, the buttons, and where the buttons link to.  
	 * @param $appId Id of app
	 * @param $recipients A comma-separated list of recipients.
	 * @param $templateParameters Parameters defining the template for the notification.  This is a Map.  Possible key values are:
	 *        <ol>  
	 *        <li> content (required) - Text content of the notification
	 *        <li> button0_surface (optional) - where button 0 should link to: "canvas" or "appProfile"
	 *        <li> button0_label (optional) - text label on button 0
	 *        <li> button1_surface (optional) - where button 1 should link to: "canvas" or "appProfile"
	 *        <li> button1_label (optional) - text label on button 1
	 *        </ol>
	 * @param $mediaItems A URI to a MySpace image, either a profile image or an album photo. External images are not allowed. 
	 *        At this time, only one media item is supported. (optional; pass null to not specify).
	 */
  public function sendNotification($appId, $recipients, $templateParams, $mediaItems) {
	if ($templateParams['content'] == null)
		throw new MySpaceException('\'content\' key required in templateParameters Map');

	// Convert templateParameters to a string representation
	$sb = '{';
	$n = count($templateParams);
	$i = 0;
 	foreach ($templateParams as $key => $val) {
 		$sb .= '"' . $key . '":"' . $val . '"';
 		$i++;
 		if ($i == $n)
 			$sb .= '}';
 		else
 			$sb .= ',';
	} 
	
	// Put mediaItems in braces, as required by the REST API
	$mediaItems = '{"' . $mediaItems . '"}';

	// Send request
	$appParams = array("recipients" => $recipients, "templateParameters" => $sb, "mediaItems" => $mediaItems);
	$REST = 'http://api.myspace.com/v1/applications/'.$appId.'/notifications';
  	return $this->context->doPut($REST, $appParams, 'POST');
  }
  
  /**
   * Clears app data for the given user id.
   * @param string $userId the user whose app data is to be cleared
   * @param string $keys semicolon separated keys to clear
   * @return true on success, false on failure
   */
  public function clearAppData($userId, $keys = null) {
  	$REST = 'http://api.myspace.com/v1/users/'.$userId.'/appdata/'.$keys;
  	return $this->context->doPut($REST, array(), 'DELETE');
  }
  
  /**
   * Stores app data for the given user id.
   * @param string $userId the user whose app data is to be cleared
   * @param hash $dataHash hash mapping keys to data
   * @return true on success, false on failure
   */
  public function putAppData($userId, $dataHash) {
  	$REST = 'http://api.myspace.com/v1/users/'.$userId.'/appdata';
  	return $this->context->doPut($REST, $dataHash, 'PUT');
  }
  
  /**
   * Fetches app data of the specified keys for the given user id.
   * @param string $userId the user whose app data is to be fetched
   * @param string $keys semicolon separated keys to fetch
   * @return App data requested
   */
  public function getAppData($userId, $keys = null) {
  	$REST = 'http://api.myspace.com/v1/users/'.$userId.'/appdata';
  	if ($keys != null)
  		$REST .= '/'.$keys;
  	$REST .= '.json';
 	$responseJSON = $this->context->call($REST);
  	return MySpaceUtils::parseJSON($responseJSON);
  }
  
  /**
   * Puts global app data 
   * @param hash $dataHash Hash of app data to put
   */
  public function putGlobalAppData($dataHash) {
  	$REST = 'http://api.myspace.com/v1/appdata/global';
  	return $this->context->doPut($REST, $dataHash, 'PUT');
  }
  
  /**
   * Gets global app data
   * @param string keys Semicolon-separated keys
   * @return 
   */
  public function getGlobalAppData($keys) {
  	$REST = 'http://api.myspace.com/v1/appdata/global';
  	if ($keys != null)
  		$REST .= '/'.$keys;
  	$REST .= '.json';
   	$responseJSON = $this->context->call($REST);
  	return MySpaceUtils::parseJSON($responseJSON);
  }
  
  /**
   * Clears global app data identified by given keys
   * @param $keys Semicolon-separated keys
   */
  public function clearGlobalAppData($keys) {
  	$REST = 'http://api.myspace.com/v1/appdata/global/' . $keys;
  	return $this->context->doPut($REST, null, 'DELETE');
  }
  
  /**
   * Fetches app data of the specified keys for the friends of the given user id.
   * @param string $userId the user whose friends' app data you want
   * @param string $keys semicolon separated keys to fetch
   * @return App data requested
   */
    public function getUserFriendsAppData($userId, $keys = null) {
  	$REST = 'http://api.myspace.com/v1/users/'.$userId.'/friends/appdata';
  	if ($keys != null)
  		$REST .= '/'.$keys;
  	$REST .= '.json';
 	$responseJSON = $this->context->call($REST);
  	return MySpaceUtils::parseJSON($responseJSON);
  }
  
  /**
   * Fetches status for the friends of the given user id.
   * @param string $userId the user whose friends' status you want
   * @return Status of friends
   */
  public function getFriendsStatus($userId) {
  	$REST = 'http://api.myspace.com/v1/users/'.$userId.'/friends/status.json';
 	$responseJSON = $this->context->call($REST);
  	return MySpaceUtils::parseJSON($responseJSON);
  }
  
  /**
   * Fetches status history for the user of the given user id.
   * @param string $userId the user whose status history you want
   * @return Status history of user
   */
  public function getStatusHistory($userId) {
	$REST = 'http://api.myspace.com/v1/users/'.$userId.'/activities.atom';
	
 	//requires a GET request, POST does not work
  	$response = $this->context->call_ATOM($REST, array('activityTypes' => 'StatusMoodUpdate'), 'GET' );

	//requires a GET request, POST does not work

  	//parseJSON is a static method and does not effect the object
  	return $response;
  }
  
  /**
   * Gets preference of a user
   * This is for onsite OpenSocial apps only
   * @param string $userId id of user 
   * @return Preference of user
   */
  public function getPreferences($userId) {
  	$REST = 'http://api.myspace.com/v1/users/'.$userId.'/preferences.json';
  	$responseJSON = $this->context->call($REST);
  	return MySpaceUtils::parseJSON($responseJSON);
  }
  
  /**
   * Gets user indicators
   * @param string $userId id of user 
   * @return User indicators
   */
  public function getIndicators($userId) {
  	$REST = 'http://api.myspace.com/v1/users/'.$userId.'/indicators.json';
  	$responseJSON = $this->context->call($REST);
  	return MySpaceUtils::parseJSON($responseJSON);
  }
}

?>